package com.kaili.basic.controller;

import com.baomidou.mybatisplus.plugins.Page;
import com.kaili.basic.pojo.dto.MdmApplicationAddDto;
import com.kaili.basic.pojo.dto.MdmApplicationModifyDto;
import com.kaili.basic.pojo.dto.MdmApplicationQueryDto;
import com.kaili.basic.pojo.entity.MdmApkInfo;
import com.kaili.basic.pojo.entity.MdmApplication;
import com.kaili.basic.pojo.entity.MdmApplicationExport;
import com.kaili.basic.pojo.vo.MdmApplicationVo;
import com.kaili.basic.service.IApplicationService;
import com.kaili.basic.util.ApkUtil;
import com.kaili.basic.version.ApiVersion;
import com.kaili.common.aop.OperateLogAspect;
import com.kaili.common.aop.log.enums.FunctionName;
import com.kaili.common.aop.log.enums.OperateType;
import com.kaili.common.exception.RestException;
import com.kaili.common.fastdfs.UploadController;
import com.kaili.common.response.CommonStatus;
import com.kaili.common.response.RestStatus;
import com.kaili.common.util.ExcelUtil;
import com.kaili.common.util.LoginDetailUtils;
import com.kaili.common.util.ObjectUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import static com.kaili.basic.util.IconUtil.extractFileFromApk;

/**
 *@Desc:应用管理控制层
 *@author:chenmengming
 *@Time: 19-7-25 3:26
 *@Copyright: @ 2019 杭州凯立通信有限公司 版权所有
 *@Warning 本内容仅限于公司内部传阅，禁止外泄或用于其他商业目的
 */
@RestController
@ApiVersion(1)
@RequestMapping("/{api_version}")
@Api(tags = "应用管理", description = "应用管理相关API")
public class MdmApplicationController {
    /**
     *  mdm应用service对象
     */
    @Autowired
    IApplicationService mdmApplicationService;

    Logger log = LoggerFactory.getLogger(MdmApplicationController.class);

    /**
     * @Desc:  mdm应用新增
     * @author: chenmengming
     * @Time: 2019/7/26 9:05
     * @param dto
     * @return com.kaili.common.response.RestStatus
     */
    @PostMapping(value = "/mdmApplication/addApplication")
    @ApiOperation(value = "新增应用",notes = "新增应用")
    public RestStatus addApplication(MdmApplicationAddDto dto,@RequestParam("file") MultipartFile file) throws IOException {
//        MdmApplication application= ObjectUtils.toObject(dto,MdmApplication.class);
        MdmApplication application=getFormData(dto, file);
        String fileName=file.getOriginalFilename();
        MdmApkInfo apkInfo=null;
        double size=file.getSize();
        if (!file.isEmpty()) {
//路径
            String path = application.getFileUrl();

//            获取Apk文件进行解析
            File ff = new File(path);
//            获取文件大小
            try {
//                size = ApkUtil.getFileSize(ff) * 1.0 / 1048576;
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println("++++++++++++++++++"+size);
            try {
                apkInfo = new ApkUtil().getApkInfo(path);
                //图标解析到地址
                extractFileFromApk(path, apkInfo.getApplicationIcon(), "D:\\projects\\mdm\\picture");
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                /*
                 * 这段代码执行完毕之后，图片上传到了工程的跟路径；
                 *  1、文件路径； 2、文件名；
                 * 3、文件格式; 4、文件大小的限制;
                 */
                BufferedOutputStream out = new BufferedOutputStream(
                        new FileOutputStream(new File(
                                file.getOriginalFilename())));
                System.out.println(file.getName());
                out.write(file.getBytes());
                out.flush();
                out.close();
            }
        catch (FileNotFoundException e) {
                e.printStackTrace();
             //   return "上传失败," + e.getMessage();
            } catch (IOException e) {
                e.printStackTrace();
              //  return "上传失败," + e.getMessage();
            }
//            return "上传成功";
        } else {
            //return "上传失败，因为文件是空的.";
        }
        application.setPackageName(apkInfo.getPackageName());//包名
        application.setSize(size);//大小
        application.setSignature(apkInfo.getApplicationLable());//签名
        application.setAppIcon(apkInfo.getApplicationIcon());//图标
        application.setUploadFiles(fileName);//文件名
        mdmApplicationService.addMdmApplication(application);
        return CommonStatus.ADD_OK;
    }

    @PostMapping(value = "/mdmApplication/uploadAppFile")
    @ApiOperation(value = "上传文件",notes = "上传文件")
    @OperateLogAspect(functionName = FunctionName.location,operateType = OperateType.ADD, key = "appTitle")
    public MdmApkInfo uploadAppFile(MdmApplicationAddDto applicationAddDto,@RequestParam("file") MultipartFile file) throws Exception {
        MdmApplication entity = getFormData(applicationAddDto, file);
        //路径
        String path = entity.getFileUrl();
        //获取Apk文件进行解析
        File ff = new File(path);
        //获取文件大小
        double size = ApkUtil.getFileSize(ff) * 1.0 / 1048576;
        MdmApkInfo apkInfo = new ApkUtil().getApkInfo(path);

        //获取根据应用名称查询获取mdm应用信息
//        MdmApplicationVo mv = mdmApplicationService.getMdmApplicationByappName(appName);
        //判断上传文件包的应用状态是否为白名单
//        if (application.getAppState() == "2") {
//            String onlineVersion = application.getVersionCode();//文件包上传的版本号
//            String localVersion = "";//本地历史的版本号
//            if (mv != null) {
//                localVersion = mv.getVersionCode();
//            }
//            //判断版本号是否需要更新
//            if (isNewVersion(localVersion, onlineVersion)) {
//                application.setCreateBy(LoginDetailUtils.getCurrentEmployeeId().longValue());
//                mdmApplicationService.addMdmApplication(application);
//            }
//        }
        return apkInfo;
    }

    /**
     * @Desc:  mdm单个应用修改
     * @author: chenmengming
     * @Time: 2019/7/26 10:03
     * @param applicationModifyDto
     * @return com.kaili.common.response.RestStatus
     */
    @PutMapping(value = "/mdmApplication/modifyApplication")
    @ApiOperation(value = "修改应用",notes = "修改应用")
    public RestStatus modifyApplication(@RequestBody MdmApplicationModifyDto applicationModifyDto){
//        applicationModifyDto.setModifyBy(LoginDetailUtils.getCurrent().getId().longValue());
        MdmApplication application= ObjectUtils.toObject(applicationModifyDto,MdmApplication.class);
            mdmApplicationService.updateMdmApplication(application);
        return CommonStatus.UPDATE_OK;
    }

    /**
     * @Desc:  mdm应用批量删除
     * @author: chenmengming
     * @Time: 2019/7/26 10:04
     * @param appIds
     * @return com.kaili.common.response.RestStatus
     */
    @DeleteMapping("/mdmApplication/{appIds}/deleteApplication")
    @ApiOperation(value = "删除应用", notes = "删除应用")
    @OperateLogAspect(functionName = FunctionName.location,operateType = OperateType.DELETE, key = "appTitle")
    public RestStatus deleteApplication(@PathVariable Long[] appIds){
        Map<String,Object> map=new HashMap<>();
        map.put("modifyBy",LoginDetailUtils.getCurrentEmployeeId().longValue());
        map.put("ids",appIds);
        mdmApplicationService.deleteMdmApplication(map);
        return CommonStatus.DELETE_OK;
    }

    /**
     * @Desc:  分页查询获取mdm应用信息
     * @author: chenmengming
     * @Time: 2019/7/26 10:04
     * @param applicationQueryDto
     * @return com.baomidou.mybatisplus.plugins.Page<com.kaili.basic.pojo.vo.MdmApplicationVo>
     */
    @GetMapping(value = "/mdmApplication/queryApplication")
    @ApiOperation(value = "分页查询应用信息",notes = "分页查询应用信息")
    public Page<MdmApplicationVo> queryApplication(@ModelAttribute MdmApplicationQueryDto applicationQueryDto){
        return mdmApplicationService.getMdmApplicationByKeywords(new Page<>(applicationQueryDto.getPage(),applicationQueryDto.getPageSize()),applicationQueryDto);
    }
    //查询白名单应用
    @GetMapping(value = "/mdmApplication/getWhiteApplication")
    @ApiOperation(value = "查询白名单应用信息",notes = "查询白名单应用信息")
    public List<MdmApplicationVo> getWhiteApplication(){
        return mdmApplicationService.getWhiteList();
    }
    //查询黑名单应用
    @GetMapping(value = "/mdmApplication/getBlackApplication")
    @ApiOperation(value = "查询白名单应用信息",notes = "查询白名单应用信息")
    public List<MdmApplicationVo> getBlackApplication(){
        return mdmApplicationService.getBlackList();
    }
    /**
     * @Desc:  通过id查询mdm应用
     * @author: chenmengming
     * @Time: 2019/7/31 10:18
     * @param id
     * @return com.kaili.basic.pojo.vo.MdmApplicationVo
     */
    @GetMapping(value = "/mdmApplication/queryApplicationById/{id}")
    @ApiOperation(value = "根据id查询应用信息",notes = "根据id查询应用信息")
    public MdmApplicationVo queryApplicationById(@PathVariable Integer id){
       return mdmApplicationService.getMdmApplicationById(id);
    }

    /**
     * @Desc:  查询所有mdm应用
     * @author: chenmengming
     * @Time: 2019/7/31 10:18
     * @param applicationQueryDto
     * @return com.kaili.basic.pojo.vo.MdmApplicationVo
     */
    @GetMapping(value = "/mdmApplication/queryApplicationInfo")
    @ApiOperation(value = "查询所有mdm应用",notes = "查询所有mdm应用")
    public List<MdmApplicationVo> queryApplicationInfo(@ModelAttribute MdmApplicationQueryDto applicationQueryDto){
        return mdmApplicationService.getMdmApplicationInfo(applicationQueryDto);
    }


    /**
     * @Desc:  mdm应用导出
     * @author: chenmengming
     * @Time: 2019/7/26 10:04
     * @param response
     * @param applicationQueryDto
     * @return void
     */
    @GetMapping(value = "/mdmApplication/applicationExport")
    @ApiOperation(value = "导出应用",notes = "导出应用")
    public void ApplicationExport(@ModelAttribute MdmApplicationQueryDto applicationQueryDto, HttpServletResponse response) throws RestException {
        applicationQueryDto.setPageSize(Integer.MAX_VALUE);
        List<MdmApplicationExport> exportList = mdmApplicationService.getApplicationExport(applicationQueryDto);
        ExcelUtil.exportExcel(exportList,"应用管理日志","sheet1", MdmApplicationExport.class, UUID.randomUUID().toString()+".xls",response);
    }

    private MdmApplication getFormData(MdmApplicationAddDto dto,MultipartFile file) {
        MdmApplication entity = new MdmApplication();
        BeanUtils.copyProperties(dto,entity);
        try {
            if (file != null && file.getSize() != 0) {
                String path = UploadController.saveFile(file);
                entity.setFileUrl(path);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return entity;
    }


//    private MdmApplication getFormData(HttpServletRequest request){
//       int id= Integer.parseInt(request.getParameter("id"));
//       String appName= request.getParameter("appName");
//       String appIcon= request.getParameter("appIcon");
//       String appState= request.getParameter("appState");
//       String terrace= request.getParameter("terrace");
//       String packageName= request.getParameter("packageName");
//       String signature= request.getParameter("signature");
//       Double size=Double.parseDouble(request.getParameter("size"));
//       String uploadFiles= request.getParameter("uploadFiles");
//       String versionCode= request.getParameter("versionCode");
//       String forceUpdate= request.getParameter("forceUpdate");
//       String fileUrl= request.getParameter("fileUrl");
//        MdmApplication mdmApplication=new MdmApplication();
//        return mdmApplication;
//    }
    /**
           * 判断是否为最新版本方法 将版本号根据.切分为int数组 比较
           *
           * @param localVersion  本地版本号
           * @param onlineVersion 线上版本号
           * @return 是否为新版本
          * @throws IllegalArgumentException argument may not be null !
          */
      public static boolean isNewVersion(String localVersion, String onlineVersion) {

                 if (localVersion == null || onlineVersion == null) {
                         throw new IllegalArgumentException("argument may not be null !");
                     }
                 if (localVersion.equals(onlineVersion)) {
                        return false;
                 }
                //过滤非数字和非字符点
                String[] localArray = localVersion.replaceAll("[^0-9.]", "").split("[.]");
                 String[] onlineArray = onlineVersion.replaceAll("[^0-9.]", "").split("[.]");
                int length = localArray.length < onlineArray.length ? localArray.length : onlineArray.length;//取长度较短的版本
                //以长度较短的版本为基点，逐个判断大小
                 for (int i = 0; i < length; i++) {
                        if (Integer.parseInt(onlineArray[i]) > Integer.parseInt(localArray[i])) {
                                 return true;
                            } else if (Integer.parseInt(onlineArray[i]) < Integer.parseInt(localArray[i])) {
                                return false;
                             }
                         // 相等 比较下一组值
                    }
                 //长度较长的判断
                //比较最后差异组数值
                if (localArray.length < onlineArray.length) {//旧版本长度短于新版本
                         return Integer.parseInt(onlineArray[onlineArray.length - 1]) > 0;
                     } else if (localArray.length > onlineArray.length) {//旧版本长度长于新版本
                         return Integer.parseInt(onlineArray[onlineArray.length - 1]) < 0;//旧版本
                     }
                 return false;
             }
}
